package weaver.interfaces.zhlx.duss.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.axis.encoding.Base64;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import weaver.alioss.AliOSSObjectManager;
import weaver.alioss.AliOSSObjectUtil;
import weaver.common.DateUtil;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.file.AESCoder;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipInputStream;

import static java.util.regex.Pattern.compile;

/**
 * @author dusongsong
 * @date 2023年08月29日 13:49
 */
public class C4Util {

    private static  JSONObject propVal = PropUtil.getPropVal("zhlxc4");
    private static  String URL = propVal.getString("url");
    private static  String USERNAME = propVal.getString("username");
    private static  String PASSWORD = propVal.getString("password");

    /**
     * 修改合同评审状态
     *
     * @param content
     * @return
     */
    public static JSONObject updateHtpsStatus(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/contract/ContractCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;

    }

    /**
     * 修改样品申请状态
     *
     * @param content
     * @return
     */
    public static JSONObject updateYpsqStatus(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/contract/ContractCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;
    }

    /**
     * 修改客户评审状态
     *
     * @param content
     * @return
     */
    public static JSONObject updateKhpsStatus(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/customer/CorporateAccountCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;
    }

    /**
     * 修改报价单状态
     *
     * @param content
     * @return
     */
    public static JSONObject updateBjdStatus(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/salesquote/SalesQuoteCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;

    }

    /**
     * 更新客户主数据
     *
     * @param content
     * @return
     */
    public static JSONObject updateKhzsj(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/customer/CorporateAccountCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;

    }

    /**
     * 创建销售数据
     *
     * @param content
     * @return
     */
    public static JSONObject createXssj(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/customer/CorporateAccountCollection('" + uuid + "')/CorporateAccountSalesData";
        JSONObject resultJson = sendPostOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;

    }

    /**
     * 更新销售主数据
     *
     * @param content
     * @return
     */
    public static JSONObject updateXssj(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/v1/customer/CorporateAccountSalesDataCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;

    }
    /**
     * 3.11.3	创建合同附件
     *
     * @param content
     * @return
     */
    public static JSONObject createHtfj(JSONObject content, Map<String, Object> dataMap) {
        String apiUrl = "/sap/c4c/odata/v1/c4codataapi/ContractAttachmentFolderCollection";
        JSONObject resultJson = sendPostOKHttpRequest(apiUrl, content.toJSONString());
        if (content.containsKey("Binary")) {
            content.put("Binary", "");
        }
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl);
        return resultJson;

    }

    /**
     * 修改客户分类评审状态
     *
     * @param content
     * @return
     */
    public static JSONObject updateKhflpsStatus(JSONObject content, Map<String, Object> dataMap) {
        String uuid = Util.null2String(dataMap.get("uuid"));
        String apiUrl = "/sap/c4c/odata/cust/v1/customerclassification/BO_CustClassificationRootCollection('" + uuid + "')";
        JSONObject resultJson = sendOKHttpRequest(apiUrl, content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, apiUrl.replace("'", ""));
        return resultJson;
    }

    private static JSONObject sendOKHttpRequest(String apiType, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        String apiUrl = URL + Util.null2String(apiType);
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("PATCH", body)
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            int responeCode = response.code();
            if (responeCode == 204) {
                code = "success";
                message = "调用成功";
            } else {
                message = "调用失败，响应码=" + responeCode;
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

    private static JSONObject sendPostOKHttpRequest(String apiType, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String message = "";
        String apiUrl = URL + Util.null2String(apiType);
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            int responeCode = response.code();
            if (responeCode == 201) {
                String responseStr = Util.null2String(response.body().string());
                try {
                    Document xmlDocument = DocumentHelper.parseText(responseStr);
                    if (xmlDocument != null) {
                        Element rootElement = xmlDocument.getRootElement();
                        Element content = rootElement.element("content");
                        Element properties = content.element("properties");
                        Element ObjectID = properties.element("ObjectID");
                        resultJson.put("data", ObjectID.getTextTrim());
                        code = "success";
                        message = "调用成功";
                    }
                } catch (Exception e) {
                    message = "调用成功，返回的XML格式异常";
                }
            } else {
                message = "调用失败，响应码=" + responeCode;
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

    public static String getUUIDByWf(String tablename, String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select uuid from " + tablename + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString("uuid"));
    }

    public static boolean isJSONObject(String str) {
        boolean flag = true;
        try {
            JSONObject.parseObject(str);
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
    //返回文件流   已经经过脱密、解压
    public static InputStream getInputStreamById(int imageFileId) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId =?";
            rs.executeQuery(sql,imageFileId);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }

                if (isonlyAliOSS) {
                    imagefile = AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imagefile;
    }


    /**
     * 插入接口日志
     *
     * @param dataMap
     * @param apiType
     */
    private static void insertApiLog(Map<String, Object> dataMap, String apiType) {
        String apiUrl = URL + Util.null2String(apiType);
        String fullDate = DateUtil.getFullDate();
        try {
            InetAddress address = InetAddress.getLocalHost();
            String serverIp = address.getHostAddress();
            dataMap.put("fwqdz", serverIp);
            dataMap.put("jkqqdz", apiUrl);
            dataMap.put("jkdysj", fullDate);
            dataMap.put("jktgf", "C4");
            insertModelData("uf_apilog", 1, dataMap);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }

    //建模权限重构
    private static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    public static int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        if("jkqqcs".equals(key) && Util.null2String(map.get(key)).length()>4000){
                            updatesql += key + "='" + map.get(key).toString().substring(0,4000) + "',";
                        }else {
                            updatesql += key + "='" + map.get(key).toString() + "',";
                        }
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        boolean flag = rs.executeUpdate(updatesql);
                        if (!flag) {
                            dataid = 0;
                        }
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return dataid;
    }

    public static String removeHtml(String str) {
        String temp = "";
        while (str.indexOf("<") >= 0) {
            int index = str.indexOf("<");
            temp += str.substring(0, index);
            str = str.substring(index + 1);
            index = str.indexOf(">");
            str = str.substring(index + 1);
        }
        temp += str;
        Pattern p = compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(temp);
        temp = m.replaceAll("");
        return temp;
    }

}
